/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.ecommerce.dao.impl;

import br.com.ecommerce.dao.FreteDAO;
import br.com.ecommerce.dao.pojo.EntityPojo;
import br.com.ecommerce.dao.pojo.Frete;
import br.com.ecommerce.exceptions.DatabaseException;
import br.com.ecommerce.exceptions.IdInvalidoException;
import br.com.ecommerce.exceptions.ObjetoInvalidoException;
import br.com.ecommerce.factory.DatabaseFactory;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Classe que implementa os métodos que manipulam a entidade Frete
 * @author Afonso
 */
public class FreteDAOImpl implements FreteDAO {

    @Override
    public void create(EntityPojo obj) throws ObjetoInvalidoException
                                                , DatabaseException {
        if (obj == null || !(obj instanceof Frete)) {
           throw new ObjetoInvalidoException("Objeto POJO é null ou "
                   + "não é do tipo Frete");
        }

        Frete frete = (Frete)obj;
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;

        try {
            sql = "insert into Frete values (FRETE_SEQ.nextval, " +
                    "'" + frete.getNomeFrete() + "', " +
                    "'" + frete.getDescricaoFrete() + "',"
                    + frete.getSituacao()+ ")";

            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            stmt.execute(sql);

            stmt.close();
            conn.close();
            
        } catch (SQLException ex) {
            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }
    }

    @Override
    public EntityPojo readById(Integer idPrimaryKey)
                        throws IdInvalidoException, DatabaseException {
        if (idPrimaryKey == null) {
           throw new IdInvalidoException("ID inválido");

        }

        Frete frete = new Frete();
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;
        try {
            sql = "SELECT * FROM FRETE WHERE ID_FRETE="+idPrimaryKey;

            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if (rs.next()) {
                frete.setIdPrimaryKey(idPrimaryKey);
                frete.setNomeFrete(rs.getString(2));
                frete.setDescricaoFrete(rs.getString(3));
                frete.setSituacao(rs.getInt(4));
                
            } else {
                 throw new DatabaseException("Não há dados na base de dados para"
                         + " a query: " + sql);

            }
            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }

        return frete;
    }

    @Override
    public List readAll() throws DatabaseException {
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;
        List<Frete> list = new ArrayList<Frete>();
        try {
            sql = "SELECT * FROM FRETE ORDER BY ID_FRETE";

            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                Frete frete = new Frete();
                frete.setIdPrimaryKey(rs.getInt(1));
                frete.setNomeFrete(rs.getString(2));
                frete.setDescricaoFrete(rs.getString(3));
                frete.setSituacao(rs.getInt(4));


//                Logger.getLogger(ClienteDAOImpl.class.getName())
//                            .log(Level.INFO, "String SQL : " + cliente.toString());

                list.add(frete);
            }


            stmt.close();
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }

        return list;

    }

    /**
     * Para entidades que não podem ter seus registros excluídos, o campo
     * situacao é alterado para o valor 0, indicando que o registro está
     * desativado
     * @param idPrimaryKey
     * @throws IdInvalidoException
     * @throws DatabaseException
     */
    @Override
    public void deleteById(Integer idPrimaryKey) throws IdInvalidoException
                                                    , DatabaseException {
        if (idPrimaryKey == null) {
           throw new IdInvalidoException("ID inválido");

        }

        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;

        try {
            sql = "UPDATE FRETE SET SITUACAO=0 "
                    + "WHERE ID_FRETE='" + idPrimaryKey+"'";

            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            stmt.execute(sql);

            stmt.close();
            conn.close();

        } catch (SQLException ex) {
            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }
    }

    @Override
    public void update(EntityPojo obj) throws ObjetoInvalidoException
                                        , DatabaseException{
        if (obj == null || !(obj instanceof Frete)) {
           throw new ObjetoInvalidoException("Objeto POJO é null ou não "
                   + "é do tipo Produto");
        }

        Frete frete = (Frete)obj;
        Connection conn = DatabaseFactory.getConnection();
        Statement stmt;
        String sql;

        try {
            sql = "UPDATE FRETE SET NOME_FRETE='" +
                    frete.getNomeFrete() + "', "
                    + "DESCRICAO_FRETE='" + frete.getDescricaoFrete() + "', "
                    + "SITUACAO=" + frete.getSituacao()
                    + " WHERE ID_FRETE = " + frete.getIdPrimaryKey();

            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.INFO, "String SQL : " + sql);

            stmt = conn.createStatement();
            stmt.execute(sql);

            stmt.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(FreteDAOImpl.class.getName())
                            .log(Level.SEVERE, ex.getMessage(), ex);

            throw new DatabaseException(ex.getMessage(), ex.getCause());
        }
    }

}
